package getimg

import (
	"BingWallpaper/dbutil"
	"BingWallpaper/entity"
	"BingWallpaper/file"
	"BingWallpaper/logger"

	"fmt"
	"os"
	"strings"
	"time"

	"encoding/json"
	"io/ioutil"
	"net/http"
)

const (
	api  = "https://cn.bing.com/HPImageArchive.aspx?format=js&n=1&idx="
	host = "https://cn.bing.com"
)

func getImgURL(index string) (imgUrl string, imgFileName string, bing entity.Bing) {
	//获取图片地址
	logger.Loginfo("从接口获取图片地址……")

	resp, err := http.Get(api + index)
	if err != nil {
		logger.Loginfo(fmt.Sprint(err))
		logger.Logerr("图片地址获取失败！")
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logger.Loginfo(fmt.Sprint(err))
		logger.Logerr("图片地址获取失败！")
	}

	err = json.Unmarshal(body, &bing)
	// logger.Loginfo(bing.Images[0].Hsh)
	// logger.Loginfo(bing.Tooltips.Loading + "\r\n" + bing.Tooltips.Next + "\r\n" + bing.Tooltips.Previous + "\r\n" + bing.Tooltips.Walle + "\r\n" + bing.Tooltips.Walls)
	//logger.Loginfo(bing.Images[0].Copyright + "\r\n" + bing.Images[0].Copyrightlink + "\r\n" + bing.Images[0].Enddate + "\r\n" + bing.Images[0].Fullstartdate + "\r\n" + bing.Images[0].Hsh + "\r\n" + bing.Images[0].Quiz + "\r\n" + bing.Images[0].Startdate)
	//logger.Loginfo(bing.Images[0].Hsh)
	if err != nil {
		logger.Loginfo(fmt.Sprint(err))
		logger.Logerr("图片地址解析失败！")
	}

	imgUrl = fmt.Sprintf("%v%v", host, bing.Images[0].URL)
	//logger.Loginfo(fmt.Sprint("图片地址为：", imgUrl))

	a := strings.Split(bing.Images[0].URL, "&")

	imgFileName = time.Now().Format("20060102-150405_") + a[len(a)-2]
	b := strings.Split(a[len(a)-3], "=")
	c := strings.Split(b[len(b)-1], ".")
	imgFileName = c[len(c)-2] + "." + c[len(c)-1]
	//imgFileName = time.Now().Format("20060102-150405_")
	//logger.Loginfo(fmt.Sprint("将要保存的图片名称为：", imgFileName))
	return imgUrl, imgFileName, bing
}

func DownLoadImg(index string, dir string) {
	fileurl, filename, bing := getImgURL(index)
	flag, _ := file.FileExists(dir + filename)
	if flag {
		logger.Loginfo(fmt.Sprint("文件已存在", filename))
	} else {
		//获取图片
		logger.Loginfo("开始下载图片……")

		resp, err := http.Get(fileurl)
		if err != nil {
			logger.Loginfo(fmt.Sprint(err))
			logger.Logerr("图片获取失败！")
		}

		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			logger.Loginfo(fmt.Sprint(err))
			logger.Logerr("图片获取失败！")
		}

		f, err := os.Create(dir + filename)
		defer f.Close()

		if err != nil {
			logger.Loginfo(fmt.Sprint(err))
			logger.Logerr("图片保存失败！")
		}

		size, err := f.Write(body)

		if err != nil {
			logger.Loginfo(fmt.Sprint(err))
			logger.Logerr("图片保存失败！")
		}
		//logger.Loginfo(dir + filename)
		logger.Loginfo(fmt.Sprintf("图片保存成功:%s：%v bytes。", filename, size))

		dbutil.Add(bing, filename)
	}

}
